<template>
    <div class="videoCourse">
        <div class="videoCourseUpload">
            <div class="explanation">
                <p>支持格式：.pdf、.docx、.xls、.xlsx、.ppt</p>
                <p>注：单个文件≤200MB</p>
            </div>
            <div class="filter">
                <span>文档类别：</span>
                <el-select
                    v-model="uploadForm.docCategory"
                    class="m-2"
                    style="width: 145px"
                >
                    <el-option
                        v-for="item in documentList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </div>
            <div
                class="uploadBox"
                :style="{height: hHeight + 'px'}"
            >
                <el-upload
                    drag
                    action="#"
                    :http-request="(res) => { return uploadVideoCourse(res) }"
                    :on-change="handleChange"
                    :file-list="fileList"
                    v-model="uploadList"
                    accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt"
                    :disabled="!isAdmin"
                    :on-success="
                        (res) => {
                            return handleExcelImportSuccess(res);
                        }
                    "
                    style="height: 200px;"
                >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div
                        class="el-upload__text"
                        style="margin-bottom: 10px;"
                    >
                        拖拽到这里
                    </div>
                    <div class="el-upload__text">
                        或者 <em>点击这里</em> 上传
                    </div>
                    <!-- <template #tip>
                        <div
                            class="el-upload__tip"
                            style="line-height: 2"
                        >
                            文件格式：.xlsx、.xls
                        </div>
                    </template> -->
                </el-upload>
            </div>

        </div>
        <div class="videoCourseList">
            <div class="filter">
                <div class="filter-item">
                    <label for="">文档类别：</label>
                    <el-select
                        v-model="searchForm.docCategory"
                        class="m-2"
                        style="width: 145px"
                    >
                        <el-option
                            v-for="item in documentList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </div>
                <div class="filter-item">
                    <label for="">文档名称：</label>
                    <el-input
                        v-model="searchForm.fileName"
                        style="width: 125px"
                    />
                </div>
                <div class="filter-item">
                    <el-button
                        size="default"
                        type="primary"
                        @click="search"
                    >查询</el-button>
                    <el-button
                        size="default"
                        @click="reset"
                    >重置</el-button>
                </div>
            </div>
            <el-table
                :data="tableData"
                style="width: 100%"
                id="inspectionTask"
            >
                <!-- <el-table-column
            prop="title"
            label="所属单位"
        >
            <template #default="scope">
                {{ depNameTranslate(scope.row.depId) }}
            </template>
        </el-table-column> -->
                <el-table-column
                    prop="fileName"
                    label="文档名称"
                />
                <el-table-column
                    prop="docCategory"
                    label="分档分类"
                    width="120"
                />
                <el-table-column
                    prop="createTime"
                    label="上传时间"
                    width="160"
                />
                <el-table-column
                    prop="createUserName"
                    label="上传人"
                    width="100"
                />
                <el-table-column
                    fixed="right"
                    label="操作"
                    width="190"
                >
                    <template #default="scope">
                        <!-- <el-button
                            type="primary"
                            size="small"
                            :icon="View"
                            v-if="tableauType != 'ppt'"
                            style="margin-right: 5px;margin-left: 0px;"
                            @click="handleClick('detail', scope.row)"
                        >
                        </el-button> -->
                        <el-button
                            type="primary"
                            size="small"
                            :icon="Download"
                            style="margin-right: 5px;margin-left: 0px;"
                            @click="handleClick('download', scope.row)"
                        >
                        </el-button>
                        <el-button
                            type="primary"
                            size="small"
                            :icon="Edit"
                            :disabled="!isAdmin"
                            style="margin-right: 5px;margin-left: 0px;"
                            @click="handleClick('edit', scope.row)"
                        >
                        </el-button>
                        <el-button
                            type="danger"
                            size="small"
                            :icon="Delete"
                            :disabled="!isAdmin"
                            style="margin-right: 0px;margin-left: 0px;"
                            @click="deleteConfirm('delete', scope.row)"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-model:current-page="searchForm.pageNo"
                v-model:page-size="searchForm.pageSize"
                layout="total, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="paginationStyle"
            />
        </div>
    </div>

    <el-dialog
        v-model="editVisible"
        :title="'编辑'"
    >
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            label-width="120px"
            class="demo-ruleForm"
            :inline="true"
        >
            <div
                class="dialogModel"
                style="margin-top: 20px"
            >
                <el-row>
                    <el-col :span="24">
                        <el-form-item
                            label="文档类别："
                            prop="title"
                            style="width: 100%;"
                        >
                            <el-select
                                v-model="ruleForm.docCategory"
                                class="m-2"
                                style="width: 400px"
                            >
                                <el-option
                                    v-for="item in documentList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item
                            label="文档名称："
                            prop="title"
                            style="width: 100%;"
                        >
                            <el-input
                                v-model="ruleForm.fileName"
                                style="width: 400px"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="editConfirm()"
                    v-loading="confirmLoading"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        v-model="dialogTableVisible"
        title="文件预览"
        width="80%"
    >
        <el-scrollbar class="containRouter">
            <div
                v-if="tableauType == 'xls'"
                style="height: 500px"
                id="tableau"
                v-html="tableau"
                class="preview-content"
            ></div>
            <div
                v-if="tableauType == 'docx'"
                class="preview-content"
                v-html="htmlContent"
            ></div>
            <div
                v-if="tableauType == 'img'"
                class="preview-content"
            >
                <el-image :src="currentRow.url"></el-image>
            </div>
        </el-scrollbar>
    </el-dialog>
</template>

<script setup>
// utils
import learningCenterHttp from "@/https/learningCenter.js";
import dataCenterHttp from "@/https/dataCenter.js";
import Storage from "@/utils/storage.js";
import moment from 'moment';
import axios from "axios";
import * as XLSX from "xlsx";
import mammoth from "mammoth";
import {
    Delete,
    Edit,
    UploadFilled,
    Upload,
    Download,
    More,
    View
} from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

let searchForm = ref({
    // depId: Storage.localGet("depId"),
    learningType: '知识库',
    fileName: '',
    docCategory: '',
    docSubclass: '',
    orderBy: '1',
    entryDate: moment().format('YYYY-MM-DD'),
    pageNo: 1,
    pageSize: 10,
});
const localTypeUnit = ref(Storage.localGet("depId"));
const roleIds = ref(Storage.localGet("roleIds"));
const roleIdsList = ref([])
roleIdsList.value = roleIds.value.split(',')
const isAdmin = ref(false);
isAdmin.value = roleIdsList.value.includes('1');
console.log(roleIdsList.value.includes(1), isAdmin.value, 'isAdmin.value')
// dict
const depIdList = ref([
    { label: "公司", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const documentList = ref([
    { label: "化验标准", value: "化验标准", },
    { label: "操作手册", value: "操作手册", },
    { label: "培训课件", value: "培训课件", },
    { label: "检测报告模板", value: "检测报告模板", },
    { label: "法规文件", value: "法规文件", },
    { label: "其他", value: "其他", },
])
const docCategoryList = ref([
    {
        label: "操作场景",
        value: "操作场景",
        children: [
            { label: "基础操作类", value: "基础操作类" },
            { label: "设备操作类", value: "设备操作类" },
            { label: "实验流程类", value: "实验流程类" },
        ]
    },
    {
        label: "安全合规",
        value: "安全合规",
        children: [
            { label: "安全防护类", value: "安全防护类" },
            { label: "合规管理类", value: "合规管理类" },
            { label: "应急处理类", value: "应急处理类" },
        ]
    },
    {
        label: "人员能力",
        value: "人员能力",
        children: [
            { label: "新员工入职", value: "新员工入职" },
            { label: "在岗员工进阶", value: "在岗员工进阶" },
            { label: "管理人员培训", value: "管理人员培训" },
        ]
    },
    {
        label: "长效管理",
        value: "长效管理",
        children: [
            { label: "质量控制类", value: "质量控制类" },
            { label: "设备维护类", value: "设备维护类" },
        ]
    },
]);
const activeName = ref('')
const docCategoryFilterList = ref([
    {
        label: "全部",
        value: "",
        radioCheck: '1',
        children: [
            { label: "最新发布", value: "1" },
            { label: "最多播放", value: "2" },
        ]
    },
    {
        label: "操作场景",
        value: "操作场景",
        radioCheck: '',
        children: [
            { label: "全部", value: "" },
            { label: "基础操作类", value: "基础操作类" },
            { label: "设备操作类", value: "设备操作类" },
            { label: "实验流程类", value: "实验流程类" },
        ]
    },
    {
        label: "安全合规",
        value: "安全合规",
        radioCheck: '',
        children: [
            { label: "全部", value: "" },
            { label: "安全防护类", value: "安全防护类" },
            { label: "合规管理类", value: "合规管理类" },
            { label: "应急处理类", value: "应急处理类" },
        ]
    },
    {
        label: "人员能力",
        value: "人员能力",
        radioCheck: '',
        children: [
            { label: "全部", value: "" },
            { label: "新员工入职", value: "新员工入职" },
            { label: "在岗员工进阶", value: "在岗员工进阶" },
            { label: "管理人员培训", value: "管理人员培训" },
        ]
    },
    {
        label: "长效管理",
        value: "长效管理",
        radioCheck: '',
        children: [
            { label: "全部", value: "" },
            { label: "质量控制类", value: "质量控制类" },
            { label: "设备维护类", value: "设备维护类" },
        ]
    },
]);
const depNameTranslate = (depId) => {
    let depName = "";
    depIdList.value.forEach((item) => {
        if (item.value == depId) {
            depName = item.label;
        }
    });
    return depName;
};
let tableData = ref([]);
let total = ref(0);
let tableau = ref(null);
let tableauType = ref('');
const handleSizeChange = (val) => {
    searchForm.value.pageSize = val;
    search();
};
const handleCurrentChange = (val) => {
    searchForm.value.pageNo = val;
    search();
};
// 重置
const reset = async () => {
    searchForm.value.fileName = ''
    searchForm.value.docCategory = ''
    searchForm.value.docSubclass = ''
    searchForm.value.orderBy = '1'
    searchForm.value.entryDate = moment().format('YYYY-MM-DD'),
        search()
}
// 查询
const search = async () => {
    const res = await learningCenterHttp.learningCenterQueryFile(searchForm.value)
    console.log(res.data.data, 'res')
    tableData.value = res.data.data.records
    total.value = res.data.data.total
}
const fileList = ref([]);
const uploadList = ref([]);
const handleChange = (file, fileList) => {
    console.log(file, fileList);
    uploadList.value = fileList;
    if (fileList.length > 1) {
        fileList.splice(0, 1);
    }
};
let uploadForm = ref({
    docCategory: '化验标准',
    docSubclass: '',
    file: null,
    fileName: '',
    id: '',
    learningType: '知识库',
})
const uploadVideoCourse = async (fileObj) => {
    console.log(fileObj, 'fileObj');
    uploadForm.value.file = fileObj.file
    uploadForm.value.fileName = fileObj.file.name
    const res = await learningCenterHttp.learningCenterUpload(uploadForm.value)
    if (res.data.code == 200) {
        ElMessage({
            message: "上传成功",
            type: "success",
        });
        search()
    } else {
        fileList.value = [];
        ElMessage({
            message: "上传失败,请重新上传",
            type: "error",
        });
    }
};
const handleExcelImportSuccess = () => {

}
const ruleForm = ref({
    docCategory: '',
    fileName: ''
})
const editVisible = ref(false)
const dialogTableVisible = ref(false)
const htmlContent = ref('');
const loading = ref(false);
const error = ref('');
const documentInfo = ref(null);
const currentRow = ref()
const handleClick = async (type, row) => {
    currentRow.value = row
    if (type == 'edit') {
        editVisible.value = true
        ruleForm.value = { ...row }
    } else if (type == 'download') {
        window.open(row.url, '_blank')
    } else if (type == 'detail') {

        if (row.url.indexOf("xls") > -1) {
            tableauType.value = 'xls'
            dialogTableVisible.value = true;
            axios
                // .get(`waterFile/${row.fileName}`, {
                .get(`${row.url}`, {
                    responseType: "arraybuffer", // 设置响应体类型为arraybuffer
                })
                .then(({ data }) => {
                    let workbook = XLSX.read(new Uint8Array(data), {
                        type: "array",
                    }); // 解析数据
                    var worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
                    tableau.value = XLSX.utils.sheet_to_html(worksheet); // 渲染
                });
            return;
        } else if (row.url.indexOf("docx") > -1) {
            tableauType.value = 'docx'
            try {
                const startTime = new Date().getTime();

                // 使用fetch API获取文档
                const response = await fetch(row.url);

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
                }

                const arrayBuffer = await response.arrayBuffer();
                const endTime = new Date().getTime();

                // 使用mammoth转换文档
                const result = await mammoth.convertToHtml({ arrayBuffer });
                htmlContent.value = result.value;

                // 设置文档信息
                documentInfo.value = {
                    source: documentUrl.value,
                    loadTime: endTime - startTime,
                    fileSize: formatFileSize(arrayBuffer.byteLength)
                };

                // 显示转换消息（如果有）
                if (result.messages.length > 0) {
                    console.log('转换消息:', result.messages);
                }
            } catch (err) {
                error.value = `加载或转换文档失败: ${err.message}`;
                console.error('加载错误:', err);
            } finally {
                loading.value = false;
            }
        } else if (row.url.indexOf("pdf") > -1) {
            tableauType.value = 'pdf'
        }
    }
}
const editConfirm = async () => {
    const res = await learningCenterHttp.learningCenterEditFile(ruleForm.value)
    if (res.data.code == 200) {
        ElMessage({
            message: "编辑成功",
            type: "success",
        });
        editVisible.value = false
        search()
    } else {
        fileList.value = [];
        ElMessage({
            message: res.data.msg,
            type: "error",
        });
    }
}
const deleteConfirm = async (type, row) => {
    ElMessageBox.confirm(
        `是否删除文档【${row.fileName}】？`,
        "删除",
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(() => {
            learningCenterHttp.learningCenterDeleteFile(row).then((res) => {
                if (res.data.code == 200) {
                    ElMessage({
                        message: "删除成功",
                        type: "success",
                    });
                    search();
                } else {
                    ElMessage({
                        message: "删除失败！",
                        type: "error",
                    });
                }
            });
        })
}
// 从URL加载文档
const loadDocumentFromUrl = async () => {
    if (!documentUrl.value) {
        error.value = '请输入文档URL';
        return;
    }

    // 验证URL格式
    if (!isValidUrl(documentUrl.value)) {
        error.value = '请输入有效的URL地址';
        return;
    }

    // 验证是否为.docx文件
    if (!documentUrl.value.toLowerCase().endsWith('.docx')) {
        error.value = '仅支持.docx格式的Word文档';
        return;
    }

    loading.value = true;
    error.value = '';
    htmlContent.value = '';
    documentInfo.value = null;

    try {
        const startTime = new Date().getTime();

        // 使用fetch API获取文档
        const response = await fetch(documentUrl.value);

        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
        }

        const arrayBuffer = await response.arrayBuffer();
        const endTime = new Date().getTime();

        // 使用mammoth转换文档
        const result = await mammoth.convertToHtml({ arrayBuffer });
        htmlContent.value = result.value;

        // 设置文档信息
        documentInfo.value = {
            source: documentUrl.value,
            loadTime: endTime - startTime,
            fileSize: formatFileSize(arrayBuffer.byteLength)
        };

        // 显示转换消息（如果有）
        if (result.messages.length > 0) {
            console.log('转换消息:', result.messages);
        }
    } catch (err) {
        error.value = `加载或转换文档失败: ${err.message}`;
        console.error('加载错误:', err);
    } finally {
        loading.value = false;
    }
};

const hHeight = ref(900)
onMounted(() => {
    hHeight.value = document.documentElement.clientHeight - 230;
    search()
})
</script>
<style lang="less" scoped>
.videoCourse {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    .videoCourseUpload {
        width: 256px !important;
        min-height: 500px;
        border-right: 1px dashed #ccc;
        margin-right: 20px;
        padding: 6px 10px;
        .explanation {
            margin-bottom: 10px;
            p {
                line-height: 1.8;
                font-size: 12px;
            }
        }
        .filter {
            display: flex;
            flex-direction: row;
            align-items: center;
            margin-bottom: 10px;
            width: 100%;
            span {
                display: inline-block;
            }
        }
    }
    .videoCourseList {
        flex: 1;
    }
}
/deep/.el-upload-dragger {
    height: 300px;
    padding-top: 80px;
}
.cardList {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}
.card-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}
.moreOpration {
    display: flex;
    flex-direction: row;
    align-items: center;
    line-height: 1.8;
    cursor: pointer;
    span {
        margin-left: 6px;
    }
}
.footerContent {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    span {
        display: flex;
        flex-direction: row;
        align-items: center;
    }
}
.preview-content {
    margin-top: 20px;
}
</style>